<?php
/*
+--------------------------------------------------------------------------
|   rongbay.com
|   =============================================
|   by Nova
|   =============================================
|   Web: http://www.rongbay.com
|   Started date : 9/23/2006
+---------------------------------------------------------------------------
*/

class ECMemcache
{
	static $identifier, $crashed = 0, $debug = 1, $get = 0, $miss=0, $replace = 0, $set=0, $del = 0;//$encoding_mode, 
	
	function ECMemcache(){}
	
	static function connect(){
		if(!CGlobal::$memcache_conid && !ECMemcache::$crashed){
			if( !function_exists('memcache_connect') ){			
				//dl("php_memcache.dll");
				//dl("php_xdebug.dll");
				ECMemcache::$crashed = 1;
				return FALSE;
			}
			
			ECMemcache::$identifier = MEMCACHE_ID;//ECMemcache::$identifier = 'rongbay.com';
			
			if(!CGlobal::$memcache_server || !count(CGlobal::$memcache_server) ){
				ECMemcache::$crashed = 1;
				return FALSE;
			}
					
			if (DEBUG)
			{
				$rtime = microtime();
				$rtime = explode(" ",$rtime);
				$rtime = $rtime[1] + $rtime[0];
				$start_rb = $rtime;
			}
				
		    for ($i = 0, $n = count(CGlobal::$memcache_server); $i < $n; $i++){
		    	
		        $server = CGlobal::$memcache_server[$i];
		        
		        if( $i < 1 ) {
		       		 CGlobal::$memcache_conid = memcache_connect($server['host'], $server['port']);
		        }
		        else {
					memcache_add_server( CGlobal::$memcache_conid, $server['host'], $server['port'] );	        	
		        }
		        
				if (DEBUG) { 
					$mtime = microtime();
					$mtime = explode(" ",$mtime);
					$mtime = $mtime[1] + $mtime[0];
					$end_rb = $mtime;			
					$load_time = round(($end_rb - $start_rb),5)."s";					 		
			    	CGlobal::$conn_debug.= " <b>Connect to Memcache server : {$server['host']} : {$server['port']} </b> [in $load_time]<br>\n";
				}
				        
		    }
		  
			if( !CGlobal::$memcache_conid ){
				ECMemcache::$crashed = 1;
				return FALSE;
			}
			
			if( function_exists('memcache_set_compress_threshold') ){
				memcache_set_compress_threshold( CGlobal::$memcache_conid, 20000, 0.2 );
			}
			
			//memcache_debug( ECMemcache::$debug );
		}
		return CGlobal::$memcache_conid;
	}
	
	static function disconnect(){
		if( CGlobal::$memcache_conid ){
			memcache_close( CGlobal::$memcache_conid );
		}
		
		return TRUE;
	}

	static function stats(){
		if(self::connect()){
			if( CGlobal::$memcache_conid ){
				return	memcache_get_stats( CGlobal::$memcache_conid );
			}
		}
		
		return TRUE;
	}
	
	static function do_put( $key, $value, $expire_time = 0 ){
		if(self::connect())
		{
			$result = memcache_replace(CGlobal::$memcache_conid, md5( ECMemcache::$identifier . $key ), $value,MEMCACHE_COMPRESSED,(int)$expire_time);
			
			if( $result == false )
			{
				if(DEBUG)
				{
					self::$set++;
					
					CGlobal::$query_debug .= "<table width='95%' border='1' cellpadding='6' cellspacing='0' bgcolor='#FEFEFE'  align='center'>
							<tr>
							 <td style='font-size:14px' bgcolor='#EFEFEF'><span style='color:blue'><b>Memcache</b></span></td>
							</tr>
							<tr>
								 <td style='font-family:courier, monaco, arial;font-size:14px;color:brown'>Set \"{$key}\" (Expire: ".($expire_time?"$expire_time  sec":" forever").") by memcache_set(".md5( ECMemcache::$identifier . $key ).");</td>
								</tr>
								<tr>
								<td style='font-size:14px' bgcolor='#EFEFEF'></td>
							</tr>
						       </table><br />\n\n";
				}
				
				$result = memcache_set( CGlobal::$memcache_conid, md5( ECMemcache::$identifier . $key ), $value,MEMCACHE_COMPRESSED,(int)$expire_time);
			}
			elseif(DEBUG)
			{
				self::$replace++;
				
				CGlobal::$query_debug .= "<table width='95%' border='1' cellpadding='6' cellspacing='0' bgcolor='#FEFEFE'  align='center'>
							<tr>
							 <td style='font-size:14px' bgcolor='#EFEFEF'><span style='color:blue'><b>Memcache</b></span></td>
							</tr>
							<tr>
								 <td style='font-family:courier, monaco, arial;font-size:14px;color:brown'>Replace \"{$key}\" (Expire: ".($expire_time?"$expire_time  sec":" forever").") by memcache_set(".md5( ECMemcache::$identifier . $key ).");</td>
								</tr>
								<tr>
								<td style='font-size:14px' bgcolor='#EFEFEF'></td>
							</tr>
						       </table><br />\n\n";
			}
			
			return $result;
		}
		
		return false;
	}
	
	static function do_get( $key )
	{
		if(self::connect())
		{
			if(is_array($key))
			{
				function encode_key($key)
				{
					return md5( ECMemcache::$identifier . $key );
				}
				
				$m_key = array_map("encode_key",$key);
				
				$return_val = memcache_get( CGlobal::$memcache_conid, $m_key);
				
				if(!empty($return_val))
				{
					$return_arr = array();
					
					if(DEBUG)
					{
						CGlobal::$query_debug .= "<table width='95%' border='1' cellpadding='6' cellspacing='0' bgcolor='#FEFEFE'  align='center'>
							<tr>
							 <td style='font-size:14px' bgcolor='#EFEFEF'><span style='color:blue'><b>Memcache get Array</b></span></td>
							</tr>";
					}
					
					foreach ($m_key as $o_key => $get_key)
					{
						if(isset($return_val[$get_key]))
						{
							$return_arr[$key[$o_key]] = $return_val[$get_key];
							
							if(DEBUG)
							{
								self::$get++;
								
								CGlobal::$query_debug .=
									"<tr>
									 <td style='font-family:courier, monaco, arial;font-size:14px;color:green'>Get \"{$key[$o_key]}\" by memcache_get($get_key); <a href=\"javascript:void(jQuery.get('/tools/mem_reset.php', { act: 'remove', id: '$get_key' } ) );\">Clear</a></td>
									</tr>";
							}
							
						}
						elseif(DEBUG) 
						{
							self::$miss++;
							
							CGlobal::$query_debug .=
								"<tr>
								 <td style='font-family:courier, monaco, arial;font-size:14px;color:red'>Miss \"{$key[$o_key]}\" by memcache_get($get_key);</td>
								</tr>";
						}
					}
					
					if(DEBUG)
					{
						CGlobal::$query_debug .=	"<tr><td style='font-size:14px' bgcolor='#EFEFEF'></td>
							</tr>
						       </table><br />\n\n";
					}
					return $return_arr;
		  		}
		  		elseif(DEBUG)//Miss all
		  		{
					CGlobal::$query_debug .= "<table width='95%' border='1' cellpadding='6' cellspacing='0' bgcolor='#FEFEFE'  align='center'>
						<tr>
						 <td style='font-size:14px' bgcolor='#EFEFEF'><span style='color:blue'><b>Memcache get Array</b></span></td>
						</tr>";
					
					self::$miss += count($m_key);
					
					foreach ($m_key as $o_key => $get_key)
					{
						
							
						CGlobal::$query_debug .=
							"<tr>
							 <td style='font-family:courier, monaco, arial;font-size:14px;color:red'>Miss \"{$key[$o_key]}\" by memcache_get($get_key);</td>
							</tr>";
					}
					
					CGlobal::$query_debug .=	"<tr><td style='font-size:14px' bgcolor='#EFEFEF'></td>
						</tr>
					       </table><br />\n\n";
	  			}
			}
			else 
			{
				$hash_key 	= md5( ECMemcache::$identifier . $key );
				$return_val = memcache_get( CGlobal::$memcache_conid, $hash_key);
		  		
				if(!($return_val===false))
				{
					if(DEBUG)
					{
						self::$get++;
						
						CGlobal::$query_debug .= "<table width='95%' border='1' cellpadding='6' cellspacing='0' bgcolor='#FEFEFE'  align='center'>
							<tr>
							 <td style='font-size:14px' bgcolor='#EFEFEF'><span style='color:blue'><b>Memcache</b></span></td>
							</tr>
							<tr>
							 <td style='font-family:courier, monaco, arial;font-size:14px;color:green'>Get \"$key\" by memcache_get($hash_key); <a href=\"javascript:void(jQuery.get('/tools/mem_reset.php', { act: 'remove', id: '$key' } ) );\">Clear</a></td>
							</tr>
							<tr>
							 <td style='font-size:14px' bgcolor='#EFEFEF'></td>
							</tr>
						       </table><br />\n\n";
					}
					//return ECMemcache::decode($return_val);
					return $return_val;
		  		}
		  		elseif(DEBUG)//Miss
		  		{
		  			self::$miss++;
		  			
					CGlobal::$query_debug .= "<table width='95%' border='1' cellpadding='6' cellspacing='0' bgcolor='#FEFEFE'  align='center'>
						<tr>
						 <td style='font-size:14px' bgcolor='#EFEFEF'><span style='color:blue'><b>Memcache</b></span></td>
						</tr>
						<tr>
							 <td style='font-family:courier, monaco, arial;font-size:14px;color:red'>Miss \"{$key}\" by memcache_get($hash_key);</td>
							</tr>
							<tr>
							<td style='font-size:14px' bgcolor='#EFEFEF'></td>
						</tr>
					       </table><br />\n\n";
	  			}
	  		}
  		}
  		return false;		
	}
	
	static function do_remove( $key ){
		if(self::connect())
		{
			if(is_array($key))
			{
				function encode_key($key)
				{
					return md5( ECMemcache::$identifier . $key );
				}
				
				$m_key = array_map("encode_key",$key);
				
				if(DEBUG)
				{
					CGlobal::$query_debug .= "<table width='95%' border='1' cellpadding='6' cellspacing='0' bgcolor='#FEFEFE'  align='center'>
						<tr>
						 <td style='font-size:14px' bgcolor='#EFEFEF'><span style='color:blue'><b>Memcache</b></span></td>
						</tr>";
				}
				
				foreach ($m_key as $o_key => $get_key)
				{
					memcache_delete( CGlobal::$memcache_conid, $get_key );
					
					if(DEBUG)
					{
						self::$del++;
						
						CGlobal::$query_debug .=
							"<tr>
							 <td style='font-family:courier, monaco, arial;font-size:14px;color:#cc0000'>Delete \"{$key[$o_key]}\" by memcache_get($get_key);</td>
							</tr>";
					}
				}
					
				if(DEBUG)
				{
					CGlobal::$query_debug .=	"<tr><td style='font-size:14px' bgcolor='#EFEFEF'></td>
						</tr>
					       </table><br />\n\n";
				}
			}
			else 
			{
				memcache_delete( CGlobal::$memcache_conid, md5( ECMemcache::$identifier . $key ) );
				
				if(DEBUG)//Del
		  		{
		  			self::$del++;
		  			
					CGlobal::$query_debug .= "<table width='95%' border='1' cellpadding='6' cellspacing='0' bgcolor='#FEFEFE'  align='center'>
						<tr>
						 <td style='font-size:14px' bgcolor='#EFEFEF'><span style='color:blue'><b>Memcache</b></span></td>
						</tr>
						<tr>
							 <td style='font-family:courier, monaco, arial;font-size:14px;color:#cc0000'>Delete \"{$key}\" by memcache_get(".md5( ECMemcache::$identifier . $key ).");</td>
							</tr>
							<tr>
							<td style='font-size:14px' bgcolor='#EFEFEF'></td>
						</tr>
					       </table><br />\n\n";
	  			}
  			}
		}
	}
	
	static function clear(){
		if(self::connect()){
			memcache_flush (CGlobal::$memcache_conid );
		}
		return true;	    	    
    }

   /* static function encode($data){
        if (ECMemcache::$encoding_mode == 'base64') { 
            return base64_encode(serialize($data));
        } else { 
            return serialize($data);
        }
    } 
    
    static function decode($data){
        if (ECMemcache::$encoding_mode == 'base64') {
            return unserialize(base64_decode($data));
        } else {
            return unserialize($data);
        }
    }*/
}
?>